const { app, BrowserWindow, screen, Tray, Menu } = require('electron');
const path = require('path');
const schedule = require('node-schedule');
const fs = require('fs');

let mainWindow;
let tray = null;

function createWindow () {
  const displayBounds = screen.getPrimaryDisplay().bounds;
  mainWindow = new BrowserWindow({
    width: 500,
    height: 500,
    x: displayBounds.width - 500 - 10,  // 增加10像素右边距
    y: displayBounds.height - 500 - 40, // 减去任务栏高度(约40像素)
    frame: false,
    alwaysOnTop: true,
    webPreferences: {
      nodeIntegration: true,
      contextIsolation: false,
    },
  });

  mainWindow.loadFile('index.html');
  mainWindow.webContents.on('did-finish-load', () => {
    mainWindow.webContents.send('set-content', config.content);
  });

  mainWindow.on('closed', function () {
    mainWindow = null;
  });
}

function createTray() {
  const iconPath = path.join(__dirname, 'icon.png'); // 需要准备一个icon.png文件
  tray = new Tray(iconPath);
  
  const contextMenu = Menu.buildFromTemplate([
    {
      label: '显示窗口',
      click: () => {
        if (!mainWindow) {
          createWindow();
        }
      }
    },
    {
      label: '退出',
      click: () => {
        app.quit();
      }
    }
  ]);
  
  tray.setToolTip('休息提醒');
  tray.setContextMenu(contextMenu);
}

let config = {};
try {
  config = JSON.parse(fs.readFileSync(path.join(__dirname, 'config.json')));
} catch (err) {
  console.error('读取配置文件失败，使用默认值');
  config = {
    interval: 30,
    duration: 15,
    content: {
      title: "摆摆头，扭扭腰，喝口水",
      message: "休息一下吧！"
    }
  };
}

app.on('ready', () => {
  createTray();
  
  try {
    const job = schedule.scheduleJob(`*/${config.interval} * * * *`, function(){
      if (!mainWindow) {
        createWindow();
        setTimeout(() => {
          if (mainWindow && !mainWindow.isDestroyed()) {
            mainWindow.close();
            mainWindow = null;
          }
        }, config.duration * 1000);
      }
    });
  } catch (err) {
    console.error('Schedule job error:', err);
  }
});

app.on('window-all-closed', function () {
  // 移除这行代码，改为空函数
  // if (process.platform !== 'darwin') app.quit();
});

app.on('activate', function () {
  if (mainWindow === null) createWindow();
});



